package com.ruoyi.business.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ruoyi.business.domain.ShopVerification;
import com.ruoyi.business.service.impl.ShopVerificationServiceImpl;
import com.ruoyi.business.websocket.WebSocketUsers;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.user.api.RemoteUserMessageService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.*;

/**
 * @author ffc
 * @version 1.0
 * @description: TODO
 * @className: RabbitMQListener
 * @date 2024/8/26 21:49
 */

@Component
public class BusinessQueueListener {

    @Autowired
    private ShopVerificationServiceImpl shopVerificationService;
    @Autowired
    private RemoteUserMessageService remoteUserMessageService;

    @RabbitListener(queues = "business_queue")
    public void listenerBusinessQueue(Message message) throws IOException {
        try {
            SysNotice sysNotice = JSON.parseObject(message.getBody(), SysNotice.class);
            List<ShopVerification> shopList = shopVerificationService.selectShopVerificationList(null);
            List<com.ruoyi.user.api.domain.Message> messages = new ArrayList<>();
            for (ShopVerification shop : shopList) {
                messages.add(new com.ruoyi.user.api.domain.Message(shop.getId(), sysNotice.getNoticeTitle(),
                        sysNotice.getNoticeContent(), "0", new Date()));
            }
            remoteUserMessageService.addBatch(messages, SecurityConstants.INNER);
            Map<String, Session> map = WebSocketUsers.getUsers();
            Set<String> keys = map.keySet();
            if (keys == null || keys.size() == 0) {
                return;
            }
            for (String item : keys) {
                Session session = map.get(item);
                System.out.println(item);
                WebSocketUsers.sendMessageToUserByText(session, new String(message.getBody()));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
